package filewriting;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;

import commonfunctions.Matrix;
public class MatlabMatrixWriter 
{

    /**
     * This method creates the file of observations.
     * 
     * @throws IOException
     */
    public static Thread startWriting(Matrix weights, String dirName)
    {
    	Thread toReturn = new WritingThread(weights, dirName);
    	toReturn.start();
    	return toReturn;
    }
    private static class WritingThread extends Thread
    {
    	private Matrix myWeights;
    	private String myDirName;
    	public WritingThread(Matrix weights, String dirName)
    	{
    		myWeights = weights;
    		myDirName = dirName;
    	}
    	public void run()
    	{
    		try
        	{ 
    			double sumOfPositives = 0;
    			for (int i = 0; i < myWeights.length(); i++)
    			{
    				for (int j = 0; j < myWeights.length(); j++)
    				{
    					if (myWeights.get(i, j) > 0.0)
    						sumOfPositives += myWeights.get(i, j);
    				}
    			}
    	        File file = new File(myDirName + "/generatedMatrix.m");
    	        //A new BufferedWriter is created
    	        Writer output = null;
    	        output = new BufferedWriter(new FileWriter(file));
    	        output.flush();

    	        output.write("function [ W ] = readFile( ~ )\n");
    	        output.write("W = zeros(" + myWeights.length() + ");\n");
    	        
    	        for (int i = 0; i < myWeights.length(); i++)
    	        {
    	        	for (int j = 0; j < myWeights.length(); j++)
    	        	{
    	        		if (Math.abs(myWeights.get(i, j)) > 0)
    	        		{
    	        			output.write("W(" + (i + 1) + ", " + (j + 1) + ") = " + 
    	        					(myWeights.get(i, j) < -1 * sumOfPositives?-1 * 
    	        							sumOfPositives:myWeights.get(i, j)) + ";\n");
    	        		}
    	        	}
    	        }
    	        
    	        output.write("end");
    	        
    	        output.close();
        	}
        	catch (Exception e)
        	{
        		System.out.println("Error writing to file.");
        	}
    	}
    }
}
